package com.ai.bitcoin.service.impl;

import com.ai.bitcoin.constant.*;
import com.ai.bitcoin.jpa.dao.*;
import com.ai.bitcoin.jpa.entity.*;
import com.ai.bitcoin.jpa.service.BccBasicInfoService;
import com.ai.bitcoin.jpa.service.UserBonusService;
import com.ai.bitcoin.output.GeneralReponse;
import com.ai.bitcoin.service.*;
import com.ai.bitcoin.service.helper.UserServiceHelper;
import com.ai.bitcoin.service.helper.WeiXinServiceHelper;
import com.ai.bitcoin.service.helper.WeixinServiceUpdateHelper;
import com.ai.bitcoin.util.DateUtil;
import com.ai.bitcoin.util.IdGeneration;
import com.ai.bitcoin.util.JacksonUtils;
import com.ai.bitcoin.util.JwtUtil;
import com.ai.bitcoin.vo.UserEncourageReq;
import com.ai.bitcoin.vo.UserEncourageResponse;
import com.ai.bitcoin.vo.WeixinGroupVo;
import com.ai.bitcoin.weixin.template.BonusChangeTemplate;
import com.ai.bitcoin.weixin.template.SendReportService;
import com.ai.bitcoin.weixin.template.TemplateManager;
import com.google.common.collect.Lists;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class WeiXinServiceImpl implements WeiXinService {
    @Autowired
    BccMarketingMessageConfigDao bccMarketingMessageConfigDao;
    @Autowired
    private UserBonusService userBonusService;
    @Autowired
    private BccBasicInfoService bccBasicInfoService;
    @Autowired
    MemberCenterService memberCenterService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private WeiXinServiceHelper weiXinServiceHelper;

    @Autowired
    private BccUserDao bitCoinWechatInfoDao;

    @Autowired
    private BccUserScanWeixinDao bccUserScanWeixinDao;

    @Autowired
    private UserServiceHelper userServiceHelper;

    @Autowired
    private BitcoinWeixinMenuDao bitcoinWeixinMenuDao;

    @Autowired
    private SendReportService sendReportService;

    @Autowired
    private UserService userService;

    @Autowired
    private ExtraRedeemCodeService extraRedeemCodeService;

    @Autowired
    private BccUserWeixinGroupInviteDao bccUserWeixinGroupInviteDao;

    @Autowired
    private BccUserWeixinGroupDao bccUserWeixinGroupDao;

    @Autowired
    private BccUserPlcEventDao bccUserPlcEventDao;

    @Value("${login.page.redirect.url}")
    private String loginPageRedirectUrl;

    @Value("${login.pic.url}")
    private String loginPicUrl;

    @Value("${PLC.subscribe.desription}")
    private String plcSubscribeDescription;

    @Value("${PLC.left.num.desription}")
    private String plcLeftNumDescription;

    @Value("${discount_card_id}")
    private String discountCardId;

    @Autowired
    private WeixinServiceUpdateHelper weixinServiceUpdateHelper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private BccBasicInfoDao bccBasicInfoDao;

    @Autowired
    private MakeHtmlService makeHtmlService;
    @Autowired
    private WxMpService wechatService;

    @Override
    public GeneralReponse signature(String reqUrl) throws Exception {

        String ticket = redisTemplate.opsForValue().get(RedisKeyInfo.SIGNATURE_INFO.key());
        if (ticket == null || StringUtils.isBlank(ticket)) {
            ticket = weiXinServiceHelper.getTicket();
        }
        List<Object> list = new ArrayList<Object>();
        if (StringUtils.isNotBlank(ticket)) {
            String noncestr = UUID.randomUUID().toString();
            String timestamp = Long.toString(System.currentTimeMillis());
            StringBuilder sb = new StringBuilder();
            sb.append("jsapi_ticket=").append(ticket).append("&");
            sb.append("noncestr=").append(noncestr).append("&");
            sb.append("timestamp=").append(timestamp).append("&");
            sb.append("url=").append(URLDecoder.decode(reqUrl, "UTF-8"));
            String signature = DigestUtils.sha1Hex(sb.toString());
            Map<String, String> hashMap = new HashMap<String, String>(4, 1.0f);
            hashMap.put("jsapi_ticket", ticket);
            hashMap.put("noncestr", noncestr);
            hashMap.put("timestamp", timestamp);
            hashMap.put("signature", signature);
            list.add(hashMap);
            return new GeneralReponse(CodeConstant.SUCCESS, list);
        }
        else {
            return new GeneralReponse(CodeConstant.BUSINESS_ERROR, null, null);
        }
    }

    @Override
    public GeneralReponse setWeiXinMenu() {
        List<BitcoinWeixinMenu> firstMenus = bitcoinWeixinMenuDao.queryFirstButton();
        if (firstMenus == null || firstMenus.isEmpty()) {
            return new GeneralReponse(CodeConstant.NO_RECORD, null, null);
        }
        Map<String, Object> parameter = new HashMap<String, Object>();

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        parameter.put("button", list);

        for (BitcoinWeixinMenu opWeixinMenu : firstMenus) {
            Map<String, Object> map = new HashMap<String, Object>();
            if (opWeixinMenu.getType() == null) {
                map.put("name", opWeixinMenu.getName());
                List<BitcoinWeixinMenu> secondMenus = bitcoinWeixinMenuDao.findAllByParentIdAndStatus(opWeixinMenu.getId(), 1);
                List<Map<String, Object>> secondList = new ArrayList<Map<String, Object>>();
                map.put("sub_button", secondList);
                for (BitcoinWeixinMenu opWeixinMenu1 : secondMenus) {
                    Map<String, Object> map1 = new HashMap<String, Object>();
                    if (opWeixinMenu1.getType() == 1) {
                        map1.put("type", WeiXinMenuConstant.VIEW);
                        map1.put("name", opWeixinMenu1.getName());
                        map1.put("url", opWeixinMenu1.getUrl());
                    }
                    else if (opWeixinMenu1.getType() == 3) {
                        map1.put("type", WeiXinMenuConstant.MINIPROGRAM);
                        map1.put("name", opWeixinMenu1.getName());
                        String[] url = StringUtils.split(opWeixinMenu1.getUrl(), "^");
                        map1.put("url", url[0]);
                        map1.put("appid", url[1]);
                        map1.put("pagepath", url[2]);
                    }
                    secondList.add(map1);
                }
            }
            else if (opWeixinMenu.getType() == 1) {
                map.put("type", WeiXinMenuConstant.VIEW);
                map.put("name", opWeixinMenu.getName());
                map.put("url", opWeixinMenu.getUrl());
            }
            else if (opWeixinMenu.getType() == 3) {
                map.put("type", WeiXinMenuConstant.MINIPROGRAM);
                map.put("name", opWeixinMenu.getName());
                String[] url = StringUtils.split(opWeixinMenu.getUrl(), "^");
                map.put("url", url[0]);
                map.put("appid", url[1]);
                map.put("pagepath", url[2]);
            }
            list.add(map);
        }
        Map<String, Object> data = weiXinServiceHelper.setWeiXinMenu(parameter);
        return new GeneralReponse(CodeConstant.SUCCESS, data);
    }

    @Override
    public GeneralReponse wxinfo(String code, String state) {
        Map<String, String> auth = weiXinServiceHelper.getWeiXinAuthAccessToken(code);
        Map<String, String> data = weiXinServiceHelper.getUserInfo(auth);
        String openId = auth.get("openId");
        BccUser wechat = new BccUser();
        Date now = new Date();
        wechat.setCreateTime(now);
        wechat.setImage(data.get("image"));
        wechat.setUpdateTime(now);
        wechat.setNickname(data.get("nickname"));
        wechat.setOpenId(openId);
        String symbol = IdGeneration.getUniqueSign();
        wechat.setSymbol(symbol);
        redisTemplate.opsForValue().set("wx_" + openId, JacksonUtils.toJson(wechat));
        userServiceHelper.updateWxUser(wechat);

        boolean flag = true;
        if (state != null && !StringUtils.isBlank(state) && !StringUtils.isEmpty(state)) {
            try {
                Claims claims = jwtUtil.parseJWT(state);
                WeixinGroupVo vo = JacksonUtils.fromJson(claims.getSubject(), WeixinGroupVo.class);
                log.debug("come in:::::是什么,{}", vo);
                if (vo != null && (vo.getGroupname() != null &&
                        !StringUtils.isEmpty(vo.getGroupname())) && (vo.getNickname() != null &&
                        !StringUtils.isEmpty(vo.getNickname()))) {
                    if (!StringUtils.equals(vo.getNickname(), data.get("nickname"))) {
                        log.error("昵称有问题，群昵称{},用户昵称{}", vo.getNickname(), data.get("nickname"));
                        flag = false;
                    }
                    if (vo.getType() == 6 && flag) { //微信群签到
                        boolean result = userServiceHelper.updateWxGroupUser(vo, openId);
                        if (result) {
                            //给openId加积分
                            UserEncourageReq userEncourageReq = new UserEncourageReq();
                            userEncourageReq.setType(6);
                            userEncourageReq.setOpenId(openId);
                            userEncourageReq.setContent(vo.getGroupname() + "签到成功");
                            userEncourageReq.setGroupName(vo.getGroupname());
                            userEncourageReq.setNickname(vo.getNickname());
                            userBonusService.sendBonus(BccUserBonusConfig.EVENT_SOURCE_MP, "0201", userEncourageReq);
                        }
                    }
                    else if ((vo.getType() == 999 || vo.getType() == 9999) && flag) {
                        userServiceHelper.updateWxGroupUser(vo, openId);
                    }
                    else if (vo.getType() == 7 && flag) {//微信群关键字命中
                        boolean result = userServiceHelper.updateWxGroupUser(vo, openId);
                        if (result) {
                            //给openId加积分
                            UserEncourageReq userEncourageReq = new UserEncourageReq();
                            userEncourageReq.setType(7);
                            userEncourageReq.setOpenId(openId);
                            userEncourageReq.setContent(vo.getContent());
                            userEncourageReq.setGroupName(vo.getGroupname());
                            userEncourageReq.setNickname(vo.getNickname());
                            userBonusService.sendBonus(BccUserBonusConfig.EVENT_SOURCE_MP, "0202", userEncourageReq);
                        }
                    }
                    else if (vo.getType() == 8 && flag) {//新人入群
                        BccUserWeixinGroupInvite bccUserWeixinGroupInvite = bccUserWeixinGroupInviteDao.findByGroupNameAndOpenId(vo.getGroupname(), openId);
                        if (bccUserWeixinGroupInvite == null) { //送奖励
                            bccUserWeixinGroupInvite = new BccUserWeixinGroupInvite();
                            bccUserWeixinGroupInvite.setGroupName(vo.getGroupname());
                            bccUserWeixinGroupInvite.setNickname(vo.getNickname());
                            bccUserWeixinGroupInvite.setOpenId(openId);
                            if (vo.getParentNickname() != null && !StringUtils.isBlank(vo.getParentNickname()) && !StringUtils.equals(vo.getParentNickname(), "你")) {
                                bccUserWeixinGroupInvite.setParentNickname(vo.getParentNickname());
                            }
                            Date now1 = new Date();
                            bccUserWeixinGroupInvite.setCreateTime(now1);
                            bccUserWeixinGroupInvite.setUpdateTime(now1);
                            bccUserWeixinGroupInviteDao.save(bccUserWeixinGroupInvite);
                            userServiceHelper.updateUserBonus(new Date(), vo.getPlc(), openId);
                            BccUser user = bitCoinWechatInfoDao.findByOpenId(openId);
                            Double bonus = 0.0;
                            if (user == null) {
                                log.error("用户不存在{}", openId);
                                redisTemplate.opsForHash().increment("unget_plc", openId, vo.getPlc());
                            }
                            else {
                                bonus = user.getBonus();
                            }
                            Integer userPlcRecordType = 14;
                            String reason = "新人入群【" + vo.getGroupname() + "】奖励";
                            weixinServiceUpdateHelper.registUserPlcRecord(openId, null, reason, userPlcRecordType, vo.getPlc());
                            Map<String, Object> datazengsong = new HashMap<>();
                            datazengsong.put("openId", openId);
                            datazengsong.put("url", "http://explorelife.vip/bitcoin/bitcoin/media/" + openId + ".png");
                            datazengsong.put("first", "您的积分(PLC)变动如下");
                            datazengsong.put("FieldName", "增加原因");
                            datazengsong.put("Account", reason);
                            datazengsong.put("change", "增加");
                            datazengsong.put("CreditChange", vo.getPlc());
                            datazengsong.put("CreditTotal", bonus);
                            sendReportService.sendTemplateMsg(TemplateManager.buildTemplateParater(new BonusChangeTemplate(), datazengsong));


                            if (vo.getParentNickname() != null && !StringUtils.isBlank(vo.getParentNickname()) && !StringUtils.equals(vo.getParentNickname(), "你")) {
                                try {
                                    BccUserWeixinGroup bccUserWeixinGroup = bccUserWeixinGroupDao.findByGroupNameAndNickname(vo.getParentNickname(), vo.getGroupname());
                                    if (bccUserWeixinGroup != null) {
                                        String openId11 = bccUserWeixinGroup.getOpenId();
                                        userServiceHelper.updateUserBonus(new Date(), vo.getParentPlc(), openId11);
                                        BccUser userParent = bitCoinWechatInfoDao.findByOpenId(openId11);
                                        Double bonus11 = 0.0;
                                        if (userParent == null) {
                                            log.error("用户不存在{}", openId11);
                                            redisTemplate.opsForHash().increment("unget_plc", openId11, vo.getParentPlc());
                                        }
                                        else {
                                            bonus11 = userParent.getBonus();
                                        }
                                        Integer userPlcRecordType11 = 15;
                                        String reason11 = "邀请新人入群【" + vo.getGroupname() + "】奖励";
                                        weixinServiceUpdateHelper.registUserPlcRecord(openId11, null, reason11, userPlcRecordType11, vo.getParentPlc());
                                        Map<String, Object> datazengsong11 = new HashMap<>();
                                        datazengsong11.put("openId", openId11);
                                        datazengsong11.put("url", "http://explorelife.vip/bitcoin/bitcoin/media/" + openId11 + ".png");
                                        datazengsong11.put("first", "您的积分(PLC)变动如下");
                                        datazengsong11.put("FieldName", "增加原因");
                                        datazengsong11.put("Account", reason11);
                                        datazengsong11.put("change", "增加");
                                        datazengsong11.put("CreditChange", vo.getParentPlc());
                                        datazengsong11.put("CreditTotal", bonus11);
                                        sendReportService.sendTemplateMsg(TemplateManager.buildTemplateParater(new BonusChangeTemplate(), datazengsong11));
                                    }
                                } catch (Exception e) {

                                }
                            }

                            if (vo.getGroupOwnerName() != null && !StringUtils.isBlank(vo.getGroupOwnerName()) && !StringUtils.equals(vo.getGroupOwnerName(), "你")) {
                                try {
                                    BccUserWeixinGroup bccUserWeixinGroup = bccUserWeixinGroupDao.findByGroupNameAndNickname(vo.getGroupOwnerName(), vo.getGroupname());
                                    if (bccUserWeixinGroup != null) {
                                        String openId11 = bccUserWeixinGroup.getOpenId();
                                        userServiceHelper.updateUserBonus(new Date(), vo.getGroupOwnerPlc(), openId11);
                                        BccUser userParent = bitCoinWechatInfoDao.findByOpenId(openId11);
                                        Double bonus11 = 0.0;
                                        if (userParent == null) {
                                            log.error("用户不存在{}", openId11);
                                            redisTemplate.opsForHash().increment("unget_plc", openId11, vo.getGroupOwnerPlc());
                                        }
                                        else {
                                            bonus11 = userParent.getBonus();
                                        }
                                        Integer userPlcRecordType11 = 16;
                                        String reason11 = "新人入群【" + vo.getGroupname() + "】群主奖励";
                                        weixinServiceUpdateHelper.registUserPlcRecord(openId11, null, reason11, userPlcRecordType11, vo.getGroupOwnerPlc());
                                        Map<String, Object> datazengsong11 = new HashMap<>();
                                        datazengsong11.put("openId", openId11);
                                        datazengsong11.put("url", "http://explorelife.vip/bitcoin/bitcoin/media/" + openId11 + ".png");
                                        datazengsong11.put("first", "您的积分(PLC)变动如下");
                                        datazengsong11.put("FieldName", "增加原因");
                                        datazengsong11.put("Account", reason11);
                                        datazengsong11.put("change", "增加");
                                        datazengsong11.put("CreditChange", vo.getGroupOwnerPlc());
                                        datazengsong11.put("CreditTotal", bonus11);
                                        sendReportService.sendTemplateMsg(TemplateManager.buildTemplateParater(new BonusChangeTemplate(), datazengsong11));
                                    }
                                } catch (Exception e) {

                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        String token = jwtUtil.createToken(wechat, JwtConstant.JWT_REFRESH_TTL);
        if (token == null) {
            log.error("jwt create token failed,{}", wechat);
        }
        wechat.setToken(token);
        String key = redisTemplate.opsForValue().get("user:scan:key:" + openId);
        if (log.isDebugEnabled()) {
            log.debug("key==={}", key);
        }
        redisTemplate.opsForValue().set("user:login:key:" + key, JacksonUtils.toJson(wechat), 10, TimeUnit.MINUTES);
        return new GeneralReponse(CodeConstant.SUCCESS, wechat);
    }

    @Override
    @Transactional
    public String selectAndRegist(String fromUserName, String toUserName, String sceneId, String source) {
        BccUserScanWeixin scanWeixin = new BccUserScanWeixin();
        scanWeixin.setCreateTime(new Date());
        scanWeixin.setOpenId(fromUserName);
        scanWeixin.setSceneId(sceneId);
        bccUserScanWeixinDao.save(scanWeixin);

        BccUser user = bitCoinWechatInfoDao.findByOpenId(fromUserName);
        String user_info = redisTemplate.opsForValue().get("wx_" + fromUserName);
        if (user == null || user_info == null || StringUtils.isBlank(user_info)) { //推送消息模板
            Object plcob = redisTemplate.opsForHash().get("unget_plc", fromUserName);
            redisTemplate.opsForHash().delete("unget_plc", fromUserName);
            Double plc = 0.0;
            if (plcob != null) {
                plc = Double.valueOf(String.valueOf(plcob));
            }
            BccUser wechat = new BccUser();
            Date now = new Date();
            wechat.setCreateTime(now);
            wechat.setUpdateTime(now);
            wechat.setOpenId(fromUserName);
            String symbol = IdGeneration.getUniqueSign();
            wechat.setSymbol(symbol);
            wechat.setBonus(200.0 + plc);
            String qrcodeUrl = weiXinServiceHelper.generatePermanentQrcode(QrCodeConstant.PERMANET_SHARE_QRCODE + fromUserName);
            wechat.setShareQrcodeUrl(qrcodeUrl);
            if (user == null) {
                bitCoinWechatInfoDao.save(wechat);
                weixinServiceUpdateHelper.registUserPlcRecord(fromUserName, null, "注册赠送", 5, 200.0);

                Map<String, Object> datazengsong = new HashMap<>();
                datazengsong.put("openId", fromUserName);
                datazengsong.put("url", "http://explorelife.vip/bitcoin/bitcoin/media/" + fromUserName + ".png");
                datazengsong.put("first", "您的积分(PLC)变动如下");
                datazengsong.put("FieldName", "增加原因");
                datazengsong.put("Account", "注册赠送");
                datazengsong.put("change", "增加");
                datazengsong.put("CreditChange", 200.0);
                datazengsong.put("CreditTotal", 200.0);
//                            data.put("Remark","您可以在网站或服务号使用积分下单抵现，10积分=1元。");
                sendReportService.sendTemplateMsg(TemplateManager.buildTemplateParater(new BonusChangeTemplate(), datazengsong));
            }
            else {
                bitCoinWechatInfoDao.updateUserQrcode(qrcodeUrl, fromUserName);
            }

            redisTemplate.opsForValue().set("user:scan:key:" + fromUserName, sceneId, 10, TimeUnit.MINUTES);
            String title = "微信登陆确认";
            String description = "二维码扫描成功，点击完成登陆!,请保存好消息中的二维码,分享并关注即可获得100PLC";
            StringBuilder result = new StringBuilder();

            result.append("<xml>")
                    .append("<ToUserName><![CDATA[").append(fromUserName).append("]]></ToUserName>")
                    .append("<FromUserName><![CDATA[").append(toUserName).append("]]></FromUserName>")
                    .append("<CreateTime>").append(System.currentTimeMillis()).append("</CreateTime>")
                    .append("<MsgType><![CDATA[news]]></MsgType>")
                    .append("<ArticleCount>1</ArticleCount>")
                    .append("<Articles>")
                    .append("<item>")
                    .append("<Title><![CDATA[").append(title).append("]]></Title>")
                    .append("<Description><![CDATA[").append(description).append("]]></Description>")
                    .append("<PicUrl><![CDATA[").append(loginPicUrl).append("]]></PicUrl>")
                    .append("<Url><![CDATA[").append(loginPageRedirectUrl).append("]]></Url>")
                    .append("</item>")
                    .append("</Articles>")
                    .append("</xml>");
            if (log.isDebugEnabled()) {
                log.debug("group xml --> {" + result + "}");
            }
            makeHtmlService.generateMedia(fromUserName, new Date());
            replyvideo(fromUserName, toUserName);
            return result.toString();
        }

        String token = jwtUtil.createToken(user, JwtConstant.JWT_REFRESH_TTL);
        if (token == null) {
            log.error("jwt create token failed,{}", user);
        }
        user.setFirstLogin(false);
        user.setToken(token);
        if (log.isDebugEnabled()) {
            log.debug("key2==={}", sceneId);
        }
        redisTemplate.opsForValue().set("user:login:key:" + sceneId, JacksonUtils.toJson(user), 10, TimeUnit.MINUTES);
        //推送已经登陆
        String content = user.getNickname() + ",您已经登陆成功\n" + DateUtil.toDateStr(new Date(), CommonConstant.TIME_PATTERN);
        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("touser", fromUserName);
        messageMap.put("msgtype", "text");
        Map<String, Object> textMap = new HashMap<>();
        textMap.put("content", content);
        messageMap.put("text", textMap);
        weiXinServiceHelper.sendMsg2Customer(messageMap);
        makeHtmlService.generateMedia(fromUserName, new Date());

        replyVideo(fromUserName);
        return "";
    }

    @Override
    public String subscribe(String fromUserName, String toUserName, String parentOpenId) {
        if (parentOpenId != null) {
            parentOpenId = parentOpenId.replaceAll(QrCodeConstant.PERMANET_SHARE_QRCODE, "");
        }

        weixinServiceUpdateHelper.registNewUser(fromUserName, toUserName, parentOpenId, "邀请新用户");
        try {
            makeHtmlService.generateMedia(fromUserName, new Date());
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
        return null;
    }

    //fix_coinid_374#openId_oaPg600IlRiyozKN0nbKLRZHXGFg_153097044417252
    @Override
    public String subscribeBccAndUser(String fromUserName, String toUserName, String parentOpenId) {
        String data = parentOpenId.replaceAll(QrCodeConstant.TEMPORY_FIX_QRCODE + "_", "");
        String[] a = data.split("#");
        String[] bcc = a[0].split("_");
        String[] openId = a[1].split("_");

        weixinServiceUpdateHelper.registNewUser(fromUserName, toUserName, openId[1], "分享新闻报告");
        BccBasicInfo info = bccBasicInfoDao.findByBccId(bcc[1]);
        if (info == null) {
            log.error("bccId{} is unknown", bcc[1]);
            return "bccid is unkonwn";
        }
        weixinServiceUpdateHelper.registSubCoin(fromUserName, toUserName, parentOpenId, bcc[1], info.getNameEn());

        makeHtmlService.generateMedia(fromUserName, new Date());
        return null;
    }

    @Override
    public String bccqrcode(String fromUserName, String toUserName, String sceneId, String source) {
        String bccId = sceneId.replaceAll(QrCodeConstant.PERMANET_BCC_QRCODE, "");

        weixinServiceUpdateHelper.registNewUser(fromUserName, toUserName, null, "分享新闻报告");
        BccBasicInfo info = bccBasicInfoDao.findByBccId(bccId);
        if (info == null) {
            log.error("bccId{} is unknown", bccId);
            return "bccid is unkonwn";
        }
        weixinServiceUpdateHelper.registSubCoin(fromUserName, toUserName, null, info.getBccId(), info.getNameEn());
        makeHtmlService.generateMedia(fromUserName, new Date());
        return null;
    }

    public void sendWechatTextMessage(UserEncourageResponse response) {
        for (String message : response.getMessageList()) {
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("touser", response.getOpenId());
            messageMap.put("msgtype", "text");
            Map<String, Object> textMap = new HashMap<>();
            textMap.put("content", message);
            messageMap.put("text", textMap);
            weiXinServiceHelper.sendMsg2Customer(messageMap);
        }
    }

    @Override
    public String replyKeywords(String content, String fromUserName, String toUserName) {
        UserEncourageReq request = new UserEncourageReq();
        request.setOpenId(fromUserName);
        request.setContent(content);
        if (content.toLowerCase().contains("我的plc")) {
            UserEncourageResponse response = userBonusService.sendBonus(BccUserBonusConfig.EVENT_SOURCE_MP, "0206", request);
            sendWechatTextMessage(response);
        }
        else if (content.toLowerCase().contains("我的邀请海报")) {
            makeHtmlService.generateMedia(fromUserName, new Date());
            return "";
        }
        else if (content.toLowerCase().contains("签到")) {
            UserEncourageResponse response = userBonusService.sendBonus(BccUserBonusConfig.EVENT_SOURCE_MP, "0102", request);
            sendWechatTextMessage(response);
        }
        else if (content.toLowerCase().contains("plc兑换码")) {
            BccUser user = new BccUser();
            user.setOpenId(fromUserName);
            GeneralReponse response = extraRedeemCodeService.getOne(user);
            if (StringUtils.equals(CodeConstant.SUCCESS, response.getCode())) {
                //成功领导兑换码
                //恭喜您！成功获得一个PLC兑换码，您的兑换码是“123KDJFJ222”,请尽快去铂链APP首页的“我的资产”中进行兑换。
                Map<String, Object> messageMap = new HashMap<>();
                messageMap.put("touser", fromUserName);
                messageMap.put("msgtype", "text");
                Map<String, Object> textMap = new HashMap<>();
                textMap.put("content", "恭喜您！成功获得一个PLC兑换码，您的兑换码是“" + response.getData() + "”,请尽快去铂链APP首页的“我的资产”中进行兑换");
                messageMap.put("text", textMap);
                weiXinServiceHelper.sendMsg2Customer(messageMap);
            }
            else if (StringUtils.equals(CodeConstant.CODE_HAS_BEEN_FINISHED, response.getCode())) {
                //兑换码已经领完
                //很遗憾，PLC兑换码已经抢光了，请下次活动再来！
                Map<String, Object> messageMap = new HashMap<>();
                messageMap.put("touser", fromUserName);
                messageMap.put("msgtype", "text");
                Map<String, Object> textMap = new HashMap<>();
                textMap.put("content", "很遗憾，PLC兑换码已经抢光了，请下次活动再来！");
                messageMap.put("text", textMap);
                weiXinServiceHelper.sendMsg2Customer(messageMap);
            }
            else if (StringUtils.equals(CodeConstant.CODE_HAS_BEEN_GET, response.getCode())) {
                //已经领取过兑换码
                //您已经领取过兑换码，请下次活动再来！
                Map<String, Object> messageMap = new HashMap<>();
                messageMap.put("touser", fromUserName);
                messageMap.put("msgtype", "text");
                Map<String, Object> textMap = new HashMap<>();
                textMap.put("content", "您已经领取过兑换码，请下次活动再来！");
                messageMap.put("text", textMap);
                weiXinServiceHelper.sendMsg2Customer(messageMap);
            }
        }
        else if (content.toLowerCase().contains("代金券")) {
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("touser", fromUserName);
            messageMap.put("msgtype", "wxcard");
            Map<String, Object> textMap = new HashMap<>();
            textMap.put("card_id", discountCardId);//卡劵id
            messageMap.put("wxcard", textMap);
            weiXinServiceHelper.sendMsg2Customer(messageMap);
        }
        else if (content.toLowerCase().contains("初级真题答案")) {
            String mediaId = "qf6EZ7NHI6bw06e85CSPPXNrfyNwJPw2ekzgBeowCk4";
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("touser", fromUserName);
            messageMap.put("msgtype", "image");
            Map<String, Object> imageMap = new HashMap<>();
            imageMap.put("media_id", mediaId);
            messageMap.put("image", imageMap);
            weiXinServiceHelper.sendMsg2Customer(messageMap);
        }
        else if (content.toLowerCase().contains("中级真题答案")) {
            String mediaId = "qf6EZ7NHI6bw06e85CSPPeBmk4BdhiRA_-vnD6LwRvA";
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("touser", fromUserName);
            messageMap.put("msgtype", "image");
            Map<String, Object> imageMap = new HashMap<>();
            imageMap.put("media_id", mediaId);
            messageMap.put("image", imageMap);
            weiXinServiceHelper.sendMsg2Customer(messageMap);
        }
        else if (content.toLowerCase().contains("高级真题答案")) {
            String mediaId = "qf6EZ7NHI6bw06e85CSPPUwSd3DlHq4QvUjD2MOvivQ";
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("touser", fromUserName);
            messageMap.put("msgtype", "image");
            Map<String, Object> imageMap = new HashMap<>();
            imageMap.put("media_id", mediaId);
            messageMap.put("image", imageMap);
            weiXinServiceHelper.sendMsg2Customer(messageMap);
        }
        else if (content.toLowerCase().contains("plc") || content.toLowerCase().contains("评链网")) {
            lookLeftPlcEncourage(fromUserName, toUserName);
            String title = "5分钟了解评链网是谁？PLC是什么？\n";
            String description = "观看完整视频，还能立即获得100PLC，快来看看吧！";
            StringBuilder result = new StringBuilder();

            result.append("<xml>")
                    .append("<ToUserName><![CDATA[").append(fromUserName).append("]]></ToUserName>")
                    .append("<FromUserName><![CDATA[").append(toUserName).append("]]></FromUserName>")
                    .append("<CreateTime>").append(System.currentTimeMillis()).append("</CreateTime>")
                    .append("<MsgType><![CDATA[news]]></MsgType>")
                    .append("<ArticleCount>1</ArticleCount>")
                    .append("<Articles>")
                    .append("<item>")
                    .append("<Title><![CDATA[").append(title).append("]]></Title>")
                    .append("<Description><![CDATA[").append(description).append("]]></Description>")
                    .append("<PicUrl><![CDATA[").append("https://zhuanchangxiu.oss-cn-hangzhou.aliyuncs.com/video.jpeg").append("]]></PicUrl>")
                    .append("<Url><![CDATA[").append("https://www.valuechain.group/template/video/index.html").append("]]></Url>")
                    .append("</item>")
                    .append("</Articles>")
                    .append("</xml>");
            if (log.isDebugEnabled()) {
                log.debug("group xml --> {" + result + "}");
            }
            return result.toString();
        }
        else {
            BccBasicInfo bccBasicInfo = bccBasicInfoService.subscribeKeywords(content);
            String eventTypeCd;
            if (bccBasicInfo != null) {
                //订阅关键字
                eventTypeCd = "0306";
                request.setBccBasicInfo(bccBasicInfo);
            }
            else {
                bccBasicInfo = bccBasicInfoService.getByKeyword(content);
                if (bccBasicInfo == null) {
                    log.debug("无关键字对应{}", content);
                    Map<String, Object> messageMap = new HashMap<>();
                    messageMap.put("touser", fromUserName);
                    messageMap.put("msgtype", "text");
                    Map<String, Object> textMap = new HashMap<>();
                    textMap.put("content", "抱歉，您输入的关键词有误！\n" +
                            " \n" +
                            "如果您想获得您的专属邀请海报，请点击下方菜单“我的-个人中心-获取更多PLC”进行获取！\n" +
                            " \n" +
                            "如果您想获取更多数字货币的每日最新分析报告，请回复数字货币的中文、英文或者简称！例如：回复关键词EOS，即可获取EOS当日最新分析报告。\n" +
                            " \n" +
                            "如果您已经购买了兑换码，想要进行兑换，" + "<a href=\"https://www.valuechain.group/template/exchangePlc.html\">请点击此处进行兑换</a>" + "！\n" +
                            " \n" +
                            "如果您不想接收太多推送消息，可在下方菜单“我的-个人中心”中把该数字货币进行取消关注。评链网一直立志于为您提供更精准、更快速、更具价值的信息推送服务，在产品优化的路上，给您带来的不便，敬请谅解！\n" +
                            " \n" +
                            "近期还有热门活动等你来参与，分享您的VIP专属邀请海报到朋友圈和微信好友，每成功关注一个人，即可获得100PLC！！！还想1分钟获取2000PLC" + "<a href=\"https://www.valuechain.group/template/newPLCAction.html\">点击获取攻略！</a>");
                    messageMap.put("text", textMap);
                    weiXinServiceHelper.sendMsg2Customer(messageMap);
                    return "";
                }
                else {
                    eventTypeCd = "0104";
                }
            }
            request.setBccBasicInfo(bccBasicInfo);
            UserEncourageResponse response = userBonusService.sendBonus(BccUserBonusConfig.EVENT_SOURCE_MP, eventTypeCd, request);
            sendWechatTextMessage(response);
        }
        return "";
    }

    public void replyVideo(String openId) {
        String title = "如何1分钟获取1000+PLC？\n";
        String description = "使用微信群发助手群发给100位好友可额外奖励200PLC，每邀请一位好友关注还能再获得100PLC，赶紧进来获取攻略吧！";
        String mediaId = "qf6EZ7NHI6bw06e85CSPPXa-zFX5Qj61o7-j6UsU-cQ";
        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("touser", openId);
        messageMap.put("msgtype", "video");
        Map<String, Object> videoMap = new HashMap<>();
        videoMap.put("media_id", mediaId);
        videoMap.put("thumb_media_id", mediaId);
        videoMap.put("title", title);
        videoMap.put("description", description);
        messageMap.put("video", videoMap);
        weiXinServiceHelper.sendMsg2Customer(messageMap);
    }

    @Override
    public String replyvideo(String fromUserName, String toUserName) {

        String title = "如何1分钟获取1000+PLC？\n";
        String description = "使用微信群发助手群发给100位好友可额外奖励200PLC，每邀请一位好友关注还能再获得100PLC，赶紧进来获取攻略吧！";
        StringBuilder result = new StringBuilder();

        result.append("<xml>")
                .append("<ToUserName><![CDATA[").append(fromUserName).append("]]></ToUserName>")
                .append("<FromUserName><![CDATA[").append(toUserName).append("]]></FromUserName>")
                .append("<CreateTime>").append(System.currentTimeMillis()).append("</CreateTime>")
                .append("<MsgType><![CDATA[news]]></MsgType>")
                .append("<ArticleCount>1</ArticleCount>")
                .append("<Articles>")
                .append("<item>")
                .append("<Title><![CDATA[").append(title).append("]]></Title>")
                .append("<Description><![CDATA[").append(description).append("]]></Description>")
                .append("<PicUrl><![CDATA[").append("https://zhuanchangxiu.oss-cn-hangzhou.aliyuncs.com/video.jpeg").append("]]></PicUrl>")
                .append("<Url><![CDATA[").append("https://www.valuechain.group/template/video/newVideo.html").append("]]></Url>")
                .append("</item>")
                .append("</Articles>")
                .append("</xml>");
        if (log.isDebugEnabled()) {
            log.debug("group xml --> {" + result + "}");
        }
        return result.toString();
    }

    @Override
    public void newUserSend(String userOpenId) {
        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("touser", userOpenId);
        Map<String, Object> textMap = new HashMap<>();
        List<BccMarketingMessageConfig> configList = bccMarketingMessageConfigDao.findByMarketingTypeCdAndEventTypeKeyOrderBySortIndex("02", "NEW_USER_SUBSCRIBE");

        if (CollectionUtils.isNotEmpty(configList)) {
            for (BccMarketingMessageConfig config : configList) {
                messageMap.put("msgtype", config.getMessageType());
                textMap.put("content", config.getMessageContent());
                messageMap.put("text", textMap);
                weiXinServiceHelper.sendMsg2Customer(messageMap);
            }
        }
    }

    @Override
    public void directRegist(String fromUserName, String toUserName) {
        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("touser", fromUserName);

        List<BccMarketingMessageConfig> configList = bccMarketingMessageConfigDao.findByMarketingTypeCdAndEventTypeKeyOrderBySortIndex("02", "OLD_USER_SUBSCRIBE");

        if (CollectionUtils.isNotEmpty(configList)) {
            for (BccMarketingMessageConfig config : configList) {
                Map<String, Object> textMap = new HashMap<>();
                messageMap.put("msgtype", config.getMessageType());
                textMap.put("content", config.getMessageContent());
                messageMap.put("text", textMap);
                weiXinServiceHelper.sendMsg2Customer(messageMap);
            }
        }
    }

    private void lookLeftPlcEncourage(String fromUserName, String toUserName) {
        List<BccUserPlcEvent> userPlcEvents = bccUserPlcEventDao.findBySourceInAndStatusOrderBySortIndexAscSourceAsc(Lists.newArrayList(1, 3), 1);
        List<BccUserPlcEvent> userPlcEvents1 = userService.findLeftEncourage(fromUserName, userPlcEvents);
        StringBuilder sb = new StringBuilder("您还有如下PLC待领取：\n\n");
        for (BccUserPlcEvent event : userPlcEvents1) {
            if (event.getNum() == 0) {
                continue;
            }
            String mpLinkUrl = event.getType() == 1 ? event.getLinkUrl() : "https://www.valuechain.group/template/video/neirong(gong).html";
            if (event.getType() == 13) {
                sb.append("【").append(event.getName()).append("】重磅推荐！使用微信群发助手，将您专属海报转发至100位好友！即可获得" + event.getPlc() + "PLC额外奖励！").append("<a href='").append(event.getLinkUrl()).append(" '>查看示例</a>\n\n");
            }
            else {
                sb.append("【").append(event.getName()).append("】还剩").append(event.getNum()).append("次,最高可获得").append(event.getPlc().intValue() * event.getNum()).append("PLC,<a href='").append(mpLinkUrl).append(" '>查看示例</a>\n\n");
            }
        }

        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("touser", fromUserName);
        messageMap.put("msgtype", "text");
        Map<String, Object> textMap = new HashMap<>();
        textMap.put("content", sb.toString());
        messageMap.put("text", textMap);
        weiXinServiceHelper.sendMsg2Customer(messageMap);
    }

}
